package com.grace.web.controller.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.grace.common.annotation.Log;
import com.grace.common.constant.HttpStatus;
import com.grace.common.core.domain.AjaxResult;
import com.grace.common.core.page.TableDataInfo;
import com.grace.common.enums.BusinessType;
import com.grace.common.enums.GraceStorageRoot;
import com.grace.common.enums.OperateTitle;
import com.grace.common.exception.file.FileSizeLimitExceededException;
import com.grace.common.exception.file.InvalidExtensionException;
import com.grace.storage.domain.SysStorage;
import com.grace.storage.enums.properties.StorageConfigProperties;
import com.grace.storage.factory.StorageFactory;
import com.grace.storage.service.StorageService;
import com.grace.system.controller.UserBaseController;
import com.grace.system.service.impl.SysConfigServiceImpl;

/**
 * 文件存储Controller
 * 
 * @author zg
 * @date 2022-10-21
 */
@RestController
@RequestMapping("/server/storage")
public class StorageServerController extends UserBaseController {
    @Autowired
    private StorageService storageServer;

    @Autowired
    private StorageFactory storageHandler;


    @Autowired
    private SysConfigServiceImpl configService;


    /**
     * 查询文件存储列表
     */
    @PreAuthorize("@ss.hasPermi('server:storage:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysStorage sysStorage) {
        startPage();
        List<SysStorage> list = storageServer.selectSysStorageList(sysStorage);
        return getDataTable(list);
    }

    /**
     * 获取文件存储详细信息
     */
    @PreAuthorize("@ss.hasPermi('server:storage:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(storageServer.selectSysStorageById(id));
    }

    /**
     * 文件上传
     * 
     * @param file
     * @return
     * @throws IOException
     * @throws InvalidExtensionException
     * @throws FileSizeLimitExceededException
     */

    @PostMapping("/upload")
    @PreAuthorize("@ss.hasPermi('server:storage:upload')")
    public AjaxResult upload(@RequestParam("file")MultipartFile file)
            throws IOException, FileSizeLimitExceededException, InvalidExtensionException {
        return success(storageHandler.get().storageUpload(file, GraceStorageRoot.UPLOAD_DIR));
    }

    /**
     * 批量文件上传
     * 
     * @param files
     * @return
     * @throws Exception
     */

    @PostMapping("/uploads")
    @PreAuthorize("@ss.hasPermi('server:storage:upload')")
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception {
        List<SysStorage> dates = new ArrayList<SysStorage>();
        for (MultipartFile file : files) {
            dates.add(storageHandler.get().storageUpload(file, GraceStorageRoot.UPLOAD_DIR));
        }
        return success(dates);
    }

    /**
     * 支持自定义返回参数
     * 
     * @param file 上传文件
     * @param code 自定义返回状态
     * @param url  自定义返回路径
     * @param msg  自定义返回消息
     * @return
     * @throws FileSizeLimitExceededException
     * @throws InvalidExtensionException
     * @throws IOException
     */
    @PostMapping("/upload/{code}/{url}/{msg}")
    @PreAuthorize("@ss.hasPermi('server:storage:upload')")
    public Map<String, Object> uploadResult(MultipartFile file, @PathVariable("code") String code,
            @PathVariable("url") String url, @PathVariable("msg") String msg)
            throws FileSizeLimitExceededException, InvalidExtensionException, IOException {
        SysStorage storageResult = storageHandler.get().storageUpload(file, GraceStorageRoot.UPLOAD_DIR);
        Map<String, Object> mm = new HashMap<>();
        mm.put(code, HttpStatus.SUCCESS);
        mm.put(url, storageResult.getDomain() + storageResult.getFk());
        mm.put(msg, "上传成功");
        return mm;
    }

    /**
     * 修改保存参数配置
     * 通过key批量保存
     * 默认设置为字符串类型
     * @param mp
     * @return
     */
    @PreAuthorize("@ss.hasPermi('server:storage:config')")
    @PostMapping("/updateConfig")
    @Log(title = OperateTitle.SYS_CONFIG,remark = "修改参数", businessType = BusinessType.UPDATE)
    public AjaxResult updateConfig(@RequestBody Map<String, Object> mp) {
        mp.put("configGroup", StorageConfigProperties.STORAGE_CONFIG_GROUP.getValue());
        return toAjax(configService.updatesByMap(mp, getUsername()));
    }

    /**
     * 删除文件存储
     */
    @PreAuthorize("@ss.hasPermi('server:storage:remove')")
    @Log(title = OperateTitle.SYS_STORAGE, businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable("ids") Long[] ids) {
        int de = 0;
        for (int index = 0; index < ids.length; index++) {
            storageHandler.get().storageDelete(storageServer.selectSysStorageById(ids[index]).getFk());
            de++;
        }
        return toAjax(de);
    }

    
}
